# -*- coding: utf-8 -*-
"""
Created on 15-12-29 上午10:34
@File: selenium_cookie.py
@Author: Liangrong Li
@Contact: liliangrong0@126.com
@Description: http://blog.csdn.net/warrior_zhang/article/details/50198699
"""


from selenium import webdriver
import time


broswer = webdriver.Firefox()

login_url = 'http://zhanzhang.baidu.com/'
user = ''
pwd = ''
# 打开登陆页
broswer.get(login_url)
time.sleep(2)
broswer.maximize_window()
time.sleep(10)
try:
    broswer.find_element_by_xpath('//*[@id="TANGRAM__PSP_4__userName"]').send_keys(user)
    print "user success!"
except:
    print "user error!"

time.sleep(1)

try:
    broswer.find_element_by_xpath('//*[@id="TANGRAM__PSP_4__password"]').send_keys(pwd)
    print "pwd success!"
except:
    print "pwd error!"
time.sleep(1)

try:
    broswer.find_element_by_xpath('//*[@id="TANGRAM__PSP_4__submit"]').click()
    print "click success!"
except:
    print "click error!"
time.sleep(3)

cur_url = broswer.current_url
if cur_url == 'http://zhanzhang.baidu.com/dashboard/index':
    print u"登陆成功",cur_url
print "================================================="
# 获取cookies
login_cookies = broswer.get_cookies()
print login_cookies
print "================================================="

filter_cookie = [item['name'] + "=" + item['value'] for item in login_cookies]
print filter_cookie

cookiestr = ';'.join(item for item in filter_cookie)
with open('cookie_zhanzhang.txt','w+') as f:
    f.write(cookiestr)
f.closed
